package com.example.hegel.goddess;

import android.app.DownloadManager;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.jsoup.helper.StringUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    public static final String FILE_NAME = "1024.txt";
    private DownloadManager downloadManager;
    private ClipboardManager clipboardManager;
    private WebService webService;
    private FileService fileService;


    private Set<String> urlSet;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        this.clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        this.downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        this.webService = new WebService();
        this.fileService = new FileService();

        try {
            this.urlSet = fileService.loadUrl(openFileInput(FILE_NAME));
            Log.d("MainActivity", "" + urlSet.size());
        } catch (IOException e) {
            //如果找不到文件，或者读取出错了，
            this.urlSet = new HashSet<>();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        final String text = getTextData();
        if (!ignoreTask(text)) {
            //添加到已下载列表
            urlSet.add("" + text.hashCode());
            saveUrl(text);

            //提交任务
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
            webService.submit(this.downloadManager, text, this);
        }

        //显示最新的一张图片
        File image = fileService.getLastImage(webService.getImageRoot());
        if (image != null) {
            ImageView imageView = findViewById(R.id.imageView);
            Picasso.with(this).load(image).into(imageView);
            Toast.makeText(this, image.getName(), Toast.LENGTH_LONG).show();
        }
    }


    private boolean ignoreTask(String text) {
        if (text == null || "".equals(text)) {
            return true;
        }

        if (!checkUrl(text)) {
            Toast.makeText(this, "忽略,无效URL", Toast.LENGTH_LONG).show();
            return true;
        }

        if (urlSet.contains("" + text.hashCode())) {
            Toast.makeText(this, "忽略,已经下载", Toast.LENGTH_LONG).show();
            return true;
        }


        return false;
    }

    private void saveUrl(String text) {

        try {
            FileOutputStream output = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
            fileService.saveUrl(output, urlSet);
        } catch (IOException e) {
            Toast.makeText(this, "保存历史任务失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @NonNull
    private String getTextData() {
        Intent intent = getIntent();
        final String extra = intent.getStringExtra(Intent.EXTRA_TEXT);

        String clipDataText = webService.getClipDataText(clipboardManager);
        return !StringUtil.isBlank(extra) ? extra : clipDataText;
    }

    private boolean checkUrl(String text) {
        try {
            new URL(text);
            return true;
        } catch (MalformedURLException e) {
            ;// ignoreTask exception
            return false;
        }
    }


}
